package handlers

import (
	"ecom-admin/cache"
	"ecom-admin/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func ProductAdd(c *gin.Context) {
	productCode := c.PostForm("productNode")
	productName := c.PostForm("productName")
	data := models.Product{
		ProductCode: productCode,
		ProductName: productName,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func ProductList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var product []models.Product

	redis_key := "product_list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.
			Offset(offset).
			Limit(size).
			Order("id asc").
			Debug().
			Find(&product)

		jsonData, _ := json.Marshal(product)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &product)
	}
	var total int64
	models.DB.Table("product").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  product,
		"total": total,
	})
	return
}
func ProductDetail(c *gin.Context) {

}
